<template>
  <div class="form-container">
    <!-- 基本信息表单 -->
    <div class="form-section">
      <h2 class="form-title">基本信息</h2>
      <el-form
        :model="baseForm"
        label-width="120px"
        ref="baseFormRef"
        :rules="baseRules"
      >
        <el-form-item label="老人姓名" prop="elderlyName" required>
          <el-select
            v-model="baseForm.elderlyName"
            placeholder="请选择老人"
            @change="handleElderlyChange"
            filterable
          >
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="`${elderly.name} (${elderly.idCard})`"
              :value="elderly.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="老人身份证号" prop="idCard">
          <el-input
            v-model="baseForm.idCard"
            placeholder="请输入老人身份证号"
            readonly
          />
        </el-form-item>

        <el-form-item label="联系方式" prop="phone">
          <el-input
            v-model="baseForm.phone"
            placeholder="请输入联系方式"
            readonly
          />
        </el-form-item>
        <el-form-item label="护理等级" prop="levelName">
          <el-input v-model="baseForm.levelName" placeholder="请输入护理等级" />
        </el-form-item>

        <el-form-item label="入住床位" prop="bed">
          <el-input
            v-model="baseForm.bed"
            placeholder="请输入入住床位"
            readonly
          />
        </el-form-item>
        <!-- 基本信息表单中的“护理员”字段 -->
  <el-form-item label="护理员" prop="caregiverName">
    <el-select
      v-model="baseForm.caregiverName"
      placeholder="自动填充护理员"
      multiple  
      :disabled="true" 
      style="width: 100%"
    >
      <!-- 下拉选项：遍历数组动态生成，与v-model绑定 -->
      <el-option
        v-for="name in baseForm.caregiverName"
        :key="name"  
        :label="name"
        :value="name"
      ></el-option>
    </el-select>
  </el-form-item>
      </el-form>
    </div>

    <!-- 申请信息部分 -->
    <div class="form-section">
      <h2 class="form-title">申请信息</h2>
      <el-form
        :model="baseForm"
        label-width="120px"
        ref="applyFormRef"
        :rules="applyRules"
      >
        <el-form-item label="陪同人" prop="companionType" required>
          <el-radio-group v-model="baseForm.companionType">
            <el-radio label="家属">家属</el-radio>
            <el-radio label="护理人员">护理人员</el-radio>
            <el-radio label="其他">其他</el-radio>
            <el-radio label="无">无</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="陪同人姓名" prop="companionName" required>
          <el-input
            v-model="baseForm.companionName"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="陪同人联系方式" prop="companionPhone" required>
          <el-input
            v-model="baseForm.companionPhone"
            placeholder="请输入"
            maxlength="11"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="请假周期" prop="leavePeriod" required>
          <el-date-picker
            v-model="baseForm.leavePeriod"
            type="daterange"
            range-separator="-"
            start-placeholder="请选择请假开始时间"
            end-placeholder="请选择预计返回时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="calculateLeaveDays"
            :disabled-date="handleDisabledDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预请假天数" prop="expectedLeaveDays">
          <el-input
            v-model="baseForm.expectedLeaveDays"
            placeholder="预请假天数"
            readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="请假理由" prop="leaveReason" required>
          <el-input
            v-model="baseForm.leaveReason"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
            rows="3"
          >
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="step-buttons">
      <el-button @click="handleGoBack" size="default">返回</el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
        size="default"
        :loading="submitLoading"
        >提交</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { listElderly } from "@/api/system/elderly";
import { addLeavemanage } from "@/api/leave/leavemanage";
import { useRouter } from "vue-router";

import useUserStore from "@/store/modules/user";
// 2. 获取用户存储实例
const userStore = useUserStore();
// 3. 在脚本中打印用户信息
console.log("当前登录用户信息：", {
  id: userStore.id,
  name: userStore.name,
  nickName: userStore.nickName,
  avatar: userStore.avatar,
  roles: userStore.roles,
  permissions: userStore.permissions,
});

import { getLeavemanage, listLeavemanage1 } from "@/api/leave/leavemanage";
import { ElMessageBox } from "element-plus";
import { getElderlyLeaveRecords } from "@/api/leave/leavemanage";
// 在合适的业务逻辑位置（比如组件的生命周期钩子、事件处理函数等）调用
// getLeavemanage(1).then(response => {
//   // response 就是接口返回的数据，里面应该包含如图所示的状态、实际返回时间等信息
//   // console.log('获取到的销假记录数据：', response);
//   // 接下来可以对 response 中的数据进行处理，比如渲染到页面上
//   console.log(response.actualEndTime);

// }).catch(error => {
//   console.error('获取销假记录失败：', error);
// });

const router = useRouter();
// 处理返回列表逻辑
function handleGoBack() {
  router.back(); // 修正为正确的返回方法
}

const handleDisabledDate = (date) => {
  // 获取当前时间的时间戳（毫秒级）
  const currentTime = new Date().getTime();
  // 获取当前日期的 0 点 0 分 0 秒时间戳（确保当天日期可选择）
  const todayStart = new Date(new Date().toLocaleDateString()).getTime();

  // 逻辑：如果是开始日期，禁用当前日期之前的日期；结束日期只需不早于开始日期（组件默认会处理）
  // 最终效果：开始日期最早选今天，且时间不能早于当前时刻（组件会自动结合时间选择限制）
  return date.getTime() < todayStart;
};

const elderlyList = ref([]);
const submitLoading = ref(false);
const selectedElderlyId = ref("");

const emit = defineEmits(["submit-success", "back-to-list"]);

const baseForm = reactive({
  elderlyName: "",
  idCard: "",
  phone: "",
  levelName: "",
  bed: "",
  caregiverName: [],
  companionType: "家属",
  companionName: "",
  companionPhone: "",
  leavePeriod: [],
  expectedLeaveDays: "",
  leaveReason: "",
  pizhun:"请假中",
});

const baseRules = reactive({
  elderlyName: [
    { required: true, message: "请选择老人姓名", trigger: "change" },
  ],
});

const applyRules = reactive({
  companionType: [
    { required: true, message: "请选择陪同人类型", trigger: "change" },
  ],
  companionName: [
    { required: true, message: "请输入陪同人姓名", trigger: "blur" },
  ],
  companionPhone: [
    { required: true, message: "请输入陪同人联系方式", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  leavePeriod: [
    { required: true, message: "请选择请假周期", trigger: "change" },
  ],
  leaveReason: [{ required: true, message: "请输入请假理由", trigger: "blur" }],
});

const baseFormRef = ref();
const applyFormRef = ref();

// 计算请假天数
const calculateLeaveDays = () => {
  if (baseForm.leavePeriod && baseForm.leavePeriod.length === 2) {
    const startDate = new Date(baseForm.leavePeriod[0]);
    const endDate = new Date(baseForm.leavePeriod[1]);
    const timeDiff = endDate.getTime() - startDate.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
    baseForm.expectedLeaveDays = daysDiff > 0 ? daysDiff.toString() : "0";
  } else {
    baseForm.expectedLeaveDays = "";
  }
};
const hasUnfinishedLeave = ref(false);
// 老人选择变化事件
const handleElderlyChange = async (selectedName) => {
  hasUnfinishedLeave.value = false;
  if (selectedName) {
    const selectedElderly = elderlyList.value.find(
      (elderly) => elderly.name === selectedName
    );
console.log("老人关联的护理员",selectedElderly.caregiverName);

    if (selectedElderly) {
      // 填充老人信息（不变）
      selectedElderlyId.value = selectedElderly.id;
      baseForm.idCard = selectedElderly.idCard || "";
      baseForm.phone = selectedElderly.contact || "";
      baseForm.levelName = selectedElderly.levelName || "";
      baseForm.bed = selectedElderly.bedNo || "";
      baseForm.caregiverName = selectedElderly.caregiverName || [];

      try {
        console.log("查询老人ID：", selectedElderly.id);
        const response = await getElderlyLeaveRecords(selectedElderly.id);
        console.log("接口返回原始数据：", response);

        // 处理返回数据（不变）
        let leaveRecords = [];
        if (Array.isArray(response.data)) {
          leaveRecords = response.data;
        } else if (typeof response.data === 'object' && response.data !== null) {
          leaveRecords = [response.data];
        }
        console.log("标准化后的请假记录数组：", leaveRecords);

        const latestRecord = leaveRecords[0];
        if (latestRecord && !latestRecord.actualEndTime) {
          hasUnfinishedLeave.value = true;
          // 关键修改：直接提示，无需确认
          ElMessage.warning(`老人${selectedElderly.name}存在未完成的请假记录（未返回），无法再次申请请假。`);
          // 立即清空选择，无需等待用户确认
          baseForm.elderlyName = "";
          selectedElderlyId.value = "";
        }
      } catch (error) {
        console.error("查询请假记录异常：", error);
        ElMessage.error("查询历史记录失败，请重试");
        baseForm.elderlyName = "";
        selectedElderlyId.value = "";
      }
    }
  } else {
    // 未选择老人时清空信息（不变）
    selectedElderlyId.value = "";
    baseForm.idCard = "";
    baseForm.phone = "";
    baseForm.levelName = "";
    baseForm.bed = "";
    baseForm.caregiverName = [];
  }
};
// 初始化时加载老人列表
onMounted(() => {
  listElderly({
    pageNum: 1,
    pageSize: 1000, // 增加每页数量
    contractStatus: "生效中",
  }).then((response) => {
    const uniqueElderlyMap = new Map();
    // 遍历老人列表，根据姓名去重
    response.rows.forEach((elderly) => {
      if (!uniqueElderlyMap.has(elderly.name)) {
        uniqueElderlyMap.set(elderly.name, elderly);
      }
    });

    // 将 Map 转换为数组
    elderlyList.value = Array.from(uniqueElderlyMap.values());
  });
});

// 对外暴露的表单验证方法
const validateForm = async () => {
  let isValid = true;
  await baseFormRef.value.validate((baseValid) => {
    if (!baseValid) isValid = false;
  });
  await applyFormRef.value.validate((applyValid) => {
    if (!applyValid) isValid = false;
  });
  return isValid;
};

// 提交表单
const handleSubmit = async () => {
  try {
    const isValid = await validateForm();
    if (!isValid) {
      ElMessage.warning("请完善所有必填的审批信息");
      return;
    }

    // 检查是否选择了老人
    if (!selectedElderlyId.value) {
      ElMessage.warning("请选择老人");
      return;
    }
    // 再次检查是否存在未完成的请假
    if (hasUnfinishedLeave.value) {
      ElMessage.error("该老人存在未完成的请假记录，无法提交新申请");
      return;
    }

    submitLoading.value = true;

    // 构建提交数据 - 根据实体类字段调整
    const submitData = {
      elderlyId: selectedElderlyId.value,
      companionType: baseForm.companionType,
      companionName: baseForm.companionName,
      companionPhone: baseForm.companionPhone,
      leaveStartTime: baseForm.leavePeriod[0], // 请假开始时间
      expectedEndTime: baseForm.leavePeriod[1], // 预请假结束时间
      expectedLeaveDays: parseInt(baseForm.expectedLeaveDays) || 0, // 预请假天数
      leaveReason: baseForm.leaveReason,
      leaveStatus: "待审核", // 请假状态：0-待审核
      pizhun:"请假中",
    };
    // 获取后端返回的请假记录ID
    const response = await addLeavemanage(submitData);
    console.log("后端返回的请假记录ID:", response);
    const leaveRecordId = response.leaveRequestId;
    console.log("请假记录id" + leaveRecordId);
    // 提取请假记录ID
    // const leaveRecordId = response.data.id;
    // ElMessage.success(`请假申请提交成功，请假记录ID：${leaveRecordId}`);

    ElMessage.success("请假申请提交成功");

    // 传递完整的表单数据到步骤二
    const stepData = {
      // 基本信息
      elderlyName: baseForm.elderlyName,
      idCard: baseForm.idCard,
      phone: baseForm.phone,
      levelName: baseForm.levelName,
      bed: baseForm.bed,
      caregiverName: baseForm.caregiverName,
      // 申请信息
      companionType: baseForm.companionType,
      companionName: baseForm.companionName,
      companionPhone: baseForm.companionPhone,
      leavePeriod: baseForm.leavePeriod,
      expectedLeaveDays: baseForm.expectedLeaveDays,
      leaveReason: baseForm.leaveReason,
      // 提交到后端的数据
      submitData: { ...submitData, id: leaveRecordId },
    };
    console.log("QQQQQQQQQQQQQQ",stepData.caregiverName);

    // 通知父组件提交成功，并传递数据到步骤二
    emit("submit-success", stepData);
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  selectedElderlyId.value = "";
  baseForm.elderlyName = "";
  baseForm.idCard = "";
  baseForm.phone = "";
  baseForm.levelName = "";
  baseForm.bed = "";
  baseForm.caregiverName = [];
  baseForm.companionType = "家属";
  baseForm.companionName = "";
  baseForm.companionPhone = "";
  baseForm.leavePeriod = [];
  baseForm.expectedLeaveDays = "";
  baseForm.leaveReason = "";

  if (baseFormRef.value) {
    baseFormRef.value.resetFields();
  }
  if (applyFormRef.value) {
    applyFormRef.value.resetFields();
  }
};

// 暴露方法给父组件
defineExpose({
  validateForm,
  resetForm,
});
</script>

<style scoped>
.form-section {
  width: 40%;
}
</style>